package libamuse

import (
	"notabug.org/apiote/amuse/accounts"
	"notabug.org/apiote/amuse/db"
	"notabug.org/apiote/amuse/datastructure"

	"notabug.org/apiote/gott"
)

func getReadlist(args ...interface{}) (interface{}, error) {
	request := args[0].(*RequestData)
	result := args[1].(*Result)
	page := args[2].(int)
	watchlist, err := db.GetReadlist(result.user.Username, request.id, page)
	result.result = &watchlist

	return gott.Tuple(args), err
}

func renderReadlist(args ...interface{}) interface{} {
	request := args[0].(*RequestData)
	result := args[1].(*Result)
	page := args[2].(int)
	readlist := result.result.(*datastructure.Readlist)
	readlist.Page = page
	readlist.Query = request.id
	result.page = result.renderer.RenderReadlist(*readlist, result.languages)

	return gott.Tuple(args)
}

func ShowReadlist(username string, auth accounts.Authentication, languages, mimetype, filter string, page int) (string, error) {
	auth.Necessary = true
	if page <= 0 {
		page = 1
	}
	request := &RequestData{id: filter, language: languages, mimetype: mimetype, auth: auth, username: username}
	r, err := gott.
		NewResult(gott.Tuple{request, &Result{}, page}).
		Bind(parseLanguage).
		Bind(verifyToken).
		Bind(verifyUser).
		Bind(getReadlist).
		Bind(createRenderer).
		Map(renderReadlist).
		Finish()

	if err != nil {
		return "", err
	} else {
		return r.(gott.Tuple)[1].(*Result).page, nil
	}
}
